Skip to content

fix(proto-plus): add context to TypeErrors during message manipulation#17682

Draft
guptaarima wants to merge 1 commit into
googleapis:mainfrom
guptaarima:fix-proto-plus-typeerror
Draft

fix(proto-plus): add context to TypeErrors during message manipulation#17682
guptaarima wants to merge 1 commit into
googleapis:mainfrom
guptaarima:fix-proto-plus-typeerror

Conversation

@guptaarima

Copy link
Copy Markdown

Summary of the issue:

Context:
When using proto-plus, if a user assigns a value of an incorrect type to a message field (e.g., assigning a List[int] to a field expecting a MutableSequence[str]), the error raised originates from the underlying protocol buffer library and lacks specific details about the source of the error within the proto-plus message structure.

Actual Behavior:
The library propagates a generic TypeError from the core protobuf implementation (e.g., TypeError: bad argument type for built-in operation). This error message is cryptic because it does not identify which message class or field name received the invalid type, making it difficult for users to pinpoint the cause of the type mismatch in their code.

Expected Behavior:
proto-plus should catch these underlying TypeError exceptions during field assignments or message merging (like MergeFrom). It should then raise a new, more informative TypeError that includes context about the specific proto-plus message class and the field name involved.

For example, an improved error message could look like:
TypeError: Invalid type for field 'field_name' in message 'MessageName'. Expected but got .

This fix will significantly improve the debuggability of type-related errors when using proto-plus.

@guptaarima guptaarima requested a review from a team as a code owner July 9, 2026 09:50

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request improves error handling in packages/proto-plus/proto/message.py by wrapping protocol buffer initialization and field assignment operations in try-except blocks. When a TypeError occurs during these operations, a more descriptive TypeError is raised with context about the class name, field key, and the underlying error. I have no feedback to provide as there are no review comments.

@parthea parthea self-assigned this Jul 9, 2026

@parthea parthea left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please could you address the lint failure? Please could you also add tests to avoid regressions? For example,


def test_invalid_initialization_type_error():
    """Verify that bad types passed to __init__ raise a descriptive TypeError."""
    class UserProfile(proto.Message):
        username = proto.Field(proto.STRING, number=1)
        age = proto.Field(proto.INT32, number=2)

    with pytest.raises(TypeError) as excinfo:
        # Passing a list where a string is expected
        UserProfile(username=["not", "a", "string"])
    
    error_msg = str(excinfo.value)
    assert "Failed to initialize UserProfile" in error_msg
    assert "Underlying error" in error_msg
    # Ensure the original exception is chained via 'from'
    assert isinstance(excinfo.value.__cause__, TypeError)


def test_invalid_assignment_type_error():
    """Verify that bad types assigned via __setattr__ raise a descriptive TypeError."""
    class UserProfile(proto.Message):
        username = proto.Field(proto.STRING, number=1)
        age = proto.Field(proto.INT32, number=2)
    profile = UserProfile()
    
    with pytest.raises(TypeError) as excinfo:
        # Assigning a dictionary where an integer is expected
        profile.age = {"invalid": "type"}
    
    error_msg = str(excinfo.value)
    assert "Failed to set field 'age' on UserProfile" in error_msg
    assert "{'invalid': 'type'}" in error_msg
    # Ensure the original exception is chained via 'from'
    assert isinstance(excinfo.value.__cause__, TypeError)

We may also need to patch proto/marshal/marshal.py as the test fails with FAILED tests/test_message.py::test_invalid_assignment_type_error - AttributeError: 'ProtoType' object has no attribute 'DESCRIPTOR'

Patch for proto/marshal/marshal.py:

diff --git a/packages/proto-plus/proto/marshal/marshal.py b/packages/proto-plus/proto/marshal/marshal.py
index 81f1a473bf8..3133467560d 100644
--- a/packages/proto-plus/proto/marshal/marshal.py
+++ b/packages/proto-plus/proto/marshal/marshal.py
@@ -224,7 +224,8 @@ class BaseMarshal:
         # annotation. We need to do the conversion based on the `value`
         # field's type.
         if isinstance(value, dict) and (
-            proto_type.DESCRIPTOR.has_options
+            hasattr(proto_type, "DESCRIPTOR")
+            and proto_type.DESCRIPTOR.has_options
             and proto_type.DESCRIPTOR.GetOptions().map_entry
         ):
             recursive_type = type(proto_type().value)

@parthea parthea assigned guptaarima and unassigned parthea Jul 9, 2026
@parthea

parthea commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Hi @guptaarima, I'm going to switch this to draft but please feel free to mark it ready for review once the presubmits are green

@parthea parthea marked this pull request as draft July 9, 2026 20:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants